<template>
  <div class="Login">
    <el-row type="flex" justify="center" align="middle" class="LoginRow">
      <el-col :xs="8" :sm="10" :md="12" :lg="16">
        <div class="LoginMain">
          <div class="LogoAndTitle-container" style="display: flex; flex-direction: row; align-items: center; justify-content: center;">
            <div class="Logo" style="display: flex; align-items: center;">
              <img src="@/assets/logo.png" alt="Logo" style="height: 40px;" />
            </div>
            <h2>IT培优综合服务平台</h2>
          </div>

          <el-form class="LoginForm" :model="form" ref="loginForm" :rules="rules" label-width="100px">
            <el-row type="flex" justify="center" align="middle">
              <el-col :span="24" class="avatar-col">
                <el-form-item label="头像">
                  <div class="avatar-upload-wrapper" style="display: flex; justify-content: center; align-items: center; width: 100%; height: 100%;">
                    <el-upload
                        class="avatar-uploader"
                        :action="baseURL() + '/file/upload'"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        style="display: flex; align-items: center;">
                      <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" style="max-width: 100px; max-height: 100px;" />
                      <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 24px;"></i>
                    </el-upload>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="昵称" prop="nickName">
                  <el-input placeholder="请输入昵称" v-model="form.nickName"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="userName">
                  <el-input placeholder="请输入用户名" v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="年龄">
                  <el-input placeholder="请输入年龄" type="number" v-model="form.age"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input placeholder="请输入邮箱" v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="phone">
                  <el-input placeholder="请输入联系方式" v-model="form.phone"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="密码" prop="password">
                  <el-input type="password" placeholder="请输入密码" v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input type="password" placeholder="请确认密码" v-model="form.confirmPassword"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="LoginButtons" style="text-align: center; margin-top: 20px;">
                  <el-button type="primary" @click="debouncedRegister" style="width: 100px;">注 册</el-button>
                  <el-link @click="backLogin" style="margin-left: 20px;">返回登录</el-link>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import {debounce} from "lodash";
import CryptoJS from "crypto-js";
export default {
  data() {
    return {
      csrfToken: '', // 存储获取到的CSRF Token
      form: {
        imageUrl: '',
        nickName: '',
        userName: '',
        password: '',
        confirmPassword: '',
        age: '',
        email: '',
        phone: '',
        role: 'ROLE_USER' // 默认角色信息
      },
      rules: {
        // 原有验证规则保持不变
        nickName: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: '请输入有效的邮箱地址',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ],
        // 修改此处，让电话号码非必填，只有在输入内容时才验证格式是否正确
        phone: [
          { validator: this.validatePhone, trigger: 'blur', required: false }
        ],
        imageUrl: [],
      },
      debouncedRegister: null // 防抖函数
    };
  },
  mounted() {
    this.debouncedRegister = debounce(this.register, 1000);
  },
  // 组件销毁时取消防抖函数
  beforeDestroy() {
    if (this.debouncedRegister) {
      this.debouncedRegister.cancel();
    }
    // 发起请求获取CSRF Token
    this.request.get("/web/token").then(res => {
      if (res.code === "200") {
        this.csrfToken = res.data.token;
      } else {
        console.error("获取CSRF Token失败");
      }
    });
  },
  methods: {
    // 在这里定义htmlEscape函数，方便组件内的其他方法调用
    htmlEscape(str) {
      return str.replace(/[&<>"'\/]/g, function (s) {
        switch (s) {
          case '&':
            return '&amp;';
          case '<':
            return '&lt;';
          case '>':
            return '&gt;';
          case '"':
            return '&quot;';
          case "'":
            return '&#39;';
          case '/':
            return '&#x2F;';
        }
      });
    },
    handleAvatarSuccess(e) {
      if (e.code === '200') {
        this.form.imageUrl = e.data;
        this.$forceUpdate();
      }
    },
    validatePassword(rule, value, callback) {
      if (value!== this.form.password) {
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      if (value &&!/^\d{11}$/.test(value)) {
        callback(new Error('请输入11位数字的电话号码'));
      } else {
        callback();
      }
    },
    register() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 如果用户没有上传头像，设置为默认图片地址
          if (!this.form.imageUrl) {
            this.form.imageUrl = "https://img2.baidu.com/it/u=2625169353,2769422191&fm=253&fmt=auto?w=800&h=800";
          }
          // 对密码进行MD5加密（原有逻辑保留）
          const hashedPassword = CryptoJS.MD5(this.form.password).toString(CryptoJS.enc.Hex);
          this.form.password = hashedPassword;
          const hashedConfirmPassword = CryptoJS.MD5(this.form.confirmPassword).toString(CryptoJS.enc.Hex);
          this.form.confirmPassword = hashedConfirmPassword;

          // 在注册方法中调用htmlEscape函数对各输入字段进行HTML转义
          this.form.nickName = this.htmlEscape(this.form.nickName);
          this.form.userName = this.htmlEscape(this.form.userName);
          this.form.email = this.htmlEscape(this.form.email);
          this.form.age = this.htmlEscape(this.form.age);
          this.form.phone = this.htmlEscape(this.form.phone);

          // 在请求头里添加CSRF Token，
          const headers = {
            'X-CSRF-Token': this.csrfToken
          };

          // 向后端发送请求
          this.request.post("/web/register", this.form, { headers }).then(res => {
            if (res.code === "200") {
              this.messageSuccess("注册成功");
              setTimeout(() => {
                this.$router.push({ name: "login" });
              }, 1000);
            } else {
              this.messageError(res.msg);
            }
          });

        }
      });
    },
    backLogin() {
      this.$router.push({name: "login"});
    },
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.errorMessage = ""; // 清除之前的错误提示（原有逻辑）
          this.loading = true; // 显示按钮加载状态（原有逻辑）

          // 确保在发送请求前对密码进行加密（原有逻辑）
          const hashedPassword = CryptoJS.MD5(this.form.password).toString(CryptoJS.enc.Hex);
          this.form.password = hashedPassword;

          // 在登录方法中调用htmlEscape函数对用户名进行HTML转义
          this.form.userName = this.htmlEscape(this.form.userName);

          // 发起登录请求
          this.request.post("/web/login", this.form)
              .then((res) => {
                this.loading = false; // 请求完成后取消加载状态（原有逻辑）

                if (res.code === "200") {
                  localStorage.setItem("user", JSON.stringify(res.data));
                  this.messageSuccess("登录成功");
                  setRoutes();

                  // 根据角色跳转（原有逻辑）
                  setTimeout(() => {
                    if (
                        res.data.role.includes("ROLE_TEACHER") ||
                        res.data.role.includes("ROLE_ADMIN")
                    ) {
                      this.$router.push({name: "backHome"});
                    } else if (res.data.role.includes("ROLE_USER")) {
                      this.$router.push({name: "frontHome"});
                    }
                  }, 1000);
                } else {
                  // 如果登录失败，显示错误信息（原有逻辑）
                  this.messageError("用户名或密码错误");
                }
              })
              .catch((error) => {
                this.loading = false; // 请求失败后取消加载状态（原有逻辑）
                console.error("登录请求失败：", error);
                this.messageError("登录失败，请稍后再试");
              });
        } else {
          // 如果表单验证失败，设置错误信息（原有逻辑）
          this.errorMessage = "请完善登录信息";
          this.messageError(this.errorMessage);
        }
      });
    },
    messageSuccess(message) {
      this.$message({type: "success", message});
    },
    messageError(message) {
      this.$message({ type: "error", message });
    }

  }
};
</script>
